<template>
  <el-scrollbar :wrap-class="{wrapClass: true}">
    <div class="app-container">
      <el-row>
        <el-col :span="12">
          <el-table v-loading="loading" :data="data" :show-header="false" width="300px">
            <el-table-column prop="icon" width="100px">
              <template slot-scope="{row}">
                <svg-icon :name="row.name" style="fill: #2787F5; stroke: white;width: 3rem;height: auto;"></svg-icon>
              </template>
            </el-table-column>
            <el-table-column prop="name" align="center">
              <template slot-scope="{row}">
                <template v-if="row.isAuthed">
                  {{row.username}}
                </template>
                <template v-else>
                  {{row.name}}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="avatar" width="100px">
              <template slot-scope="{row}">
                <template v-if="row.isAuthed">
                  <el-image :src="row.avatar"></el-image>
                </template>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="{row, $index}">
                <el-button v-if="!row.isAuthed" @click="handleClick($index)">授权</el-button>
                <el-button v-else type="danger" @click="cancelBind($index)">取消授权</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
  </el-scrollbar>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { getAction, postAction, getUrlAction, postUrlAction, deleteAction } from '@/api/common'

@Component({
  name: 'social-account-bind'
})
export default class extends Vue {
  private data : {name: string, url: string}[] = []

  private loading = true

  created() {
    this.fetchData()
  }

  private async fetchData() {
    this.loading = true
    const res = await getAction({}, 'BindingAccount/SocialList')
    this.data = res.data
    this.loading = false
  }

  private handleClick(index: number) {
    this.loading = true
    this.$common.ExeInvoke(async formProcess => {
      const authBack = formProcess.Auth(this.data[index].url)
      const reg = /^https:\/\/oauth\.vk\.com\/blank\.html/
      if (reg.test(authBack)) {
        const resp = await postAction({ type: this.data[index].name, value: authBack }, 'BindingAccount')
        this.$message.success('绑定成功')
        await this.fetchData()
        this.loading = false
      }
    })
  }

  async cancelBind(index: number) {
    this.loading = true
    const resp = await postAction({ type: this.data[index].name }, 'BindingAccount/Cancel')
    this.$message.success('取消绑定')
    await this.fetchData()
    this.loading = false
  }
}
</script>

<style scoped>

</style>
